<template>
  <a-modal v-model:open="isShow" title="新增" @cancel="handleCancel" style="width: 700px">
    <a-form
        ref="Form"
        :model="baseData"
        :rules="rules"
        :label-col="{span: 6}"
        :wrapper-col="{span: 15}"
    >
      <a-row>
        <a-col :span="24" v-for="(item,index) in formItem" :key="index">
          <a-form-item :ref="item.value" :label="item.label" :name="item.value">
            <a-input v-if="item.type === 'input'" v-model:value="baseData[item.value]" />
            <a-select v-else-if="item.type ==='select'" @change="handleSelectChange" v-model:value="baseData[item.value]" :options="item.options" allow-clear />
            <a-date-picker style="width: 100%" value-format="YYYY-MM-DD" v-else-if="item.type === 'date'" v-model:value="baseData[item.value]" />
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>
    <template #footer>
      <a-button @click="handleCancel">取消</a-button>
      <a-button type="primary" :loading="btnLoading" @click="handleOk">确定</a-button>
    </template>
  </a-modal>
</template>
<script setup>
import { ref, defineProps, defineEmits,watch,computed  } from 'vue'
import {message} from "ant-design-vue";
const props = defineProps({
  addForm:{
    type:Boolean
  },
  rules:{
    type: Object,
    default: () => ({})
  },
  formItem:{
    type: Array,
    default: () => ([]),
    required:true
  }
})
const Form = ref()
const isShow = computed(()=>{
  return props.addForm
})
const emit = defineEmits(['close','submit'])
const baseData = ref({})
const btnLoading = ref(false)
const handleCancel = () => {
  emit('close')
  baseData.value = {}
  Form.value.resetFields()
}
const handleSelectChange = (value, option) => {
  if(value){
    console.log(value, option)
    for (let optionKey in option) {
      baseData.value[optionKey] = option[optionKey]
    }
  }
}
const handleOk = async () => {
  const val = await Form.value.validate()
  try{
    btnLoading.value = true
    emit('submit',baseData.value)
  }catch (e){
    message.error(e)
  }finally {
    btnLoading.value = false
  }
}
watch(() => isShow.value,(val)=>{
  if(val){
    for (let formItemElement of props.formItem) {
      baseData.value[formItemElement.value] = ''
    }
  }
})
</script>
<style scoped>

</style>
